package com.itheima.app.cotroller;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserManager userManager;

    @PostMapping("/user/save")
    public ResponseEntity save(@RequestBody User user){
        return userManager.save(user);
    }

    @GetMapping("/user/findByPhone")
    public ResponseEntity findByPhone(String phone){
        return userManager.findByPhone(phone);
    }

    //发送验证码
    @PostMapping("/user/login")
    public void sendSms(@RequestBody Map<String,String> map){
        //1、获取手机号，2、调用UserManager来返回结果
        String phone = map.get("phone");
        userManager.sendSms(phone);
    }

    //校验登入信息,注册或登入
    @PostMapping("/user/loginVerification")
    public ResponseEntity regAndLogin(@RequestBody Map<String,String> map){
        //1、获取用户发来的手机号和验证码
        //2、调用UserManager来进行校验，并返回结果
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");
        return userManager.regAndLogin(phone,verificationCode);
    }

    //完善用户基本信息userInfo
    @PostMapping("/user/loginReginfo")
    public void saveUserInfoBase(@RequestBody UserInfo userInfo , @RequestHeader("Authorization") String token){
        userManager.saveUserInfoBase( userInfo , token);
    }

    //根据id更新用户头像
    @PostMapping({
            "/user/loginReginfo/head",
            "/users/header"
    })
    public ResponseEntity saveUserInfoHead( MultipartFile headPhoto , @RequestHeader("Authorization") String token) throws IOException {
        return  userManager.saveUserInfoHead(headPhoto,token);
    }

    //查询用户信息，根据用户Id 环信id，以及token
    @GetMapping("/users")
    public ResponseEntity findUserInfoVo(Long userID , Long huanxinID , @RequestHeader("Authorization") String token){
        if (userID != null){
            return userManager.findUserInfoVo(userID);
        }else if (huanxinID != null){
            return userManager.findUserInfoVo(huanxinID);
        }else {
            User user = userManager.findByToken(token);
            return userManager.findUserInfoVo(user.getId());
        }
    }

    //更新用户信息，
    @PutMapping("/users")
    public void updateUserInfoBase( UserInfo userInfo ){
        userManager.updateUserInfoBase(userInfo);
    }

}
